package com.linkoog.devtools.action_test;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.util.indexing.FileBasedIndex;
import com.linkoog.devtools.type_index.ClassFieldIndex;
import org.jetbrains.annotations.NotNull;

public class ClassTestAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        // 获取 PsiElement
        Project project = event.getData(CommonDataKeys.PROJECT);
        PsiElement element = event.getData(CommonDataKeys.PSI_ELEMENT);


        if (element instanceof PsiClass) {
            PsiClass psiClass = (PsiClass) element;
            // 当前选中的是一个类
            String className = psiClass.getQualifiedName();
            System.out.println("Selected class: " + className);

            // 示例：获取类的字段信息
            for (PsiField field : psiClass.getFields()) {
                System.out.println("Field: " + field.getName() + " Type: " + field.getType().getCanonicalText());
            }

            FileBasedIndex.getInstance().processValues(
                    ClassFieldIndex.INDEX_ID,
                    className,
                    null,
                    (file, value) -> {
                        System.out.println("Found in file: " + file.getPath());
                        for (String fieldInfo : value) {
                            System.out.println("Field: " + fieldInfo);
                        }
                        return true;
                    },
                    GlobalSearchScope.projectScope(project)
            );
        } else {
            // 当前选中元素不是一个类
            System.out.println("Selected element is not a class.");
        }
    }

    @Override
    public void update(@NotNull AnActionEvent event) {
        // 获取 PsiElement
        PsiElement element = event.getData(CommonDataKeys.PSI_ELEMENT);

        // 设置动作的可用性
        boolean isClass = element instanceof PsiClass;
        event.getPresentation().setEnabledAndVisible(isClass);
    }
}
